<?php
namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Gregwar\Captcha\CaptchaBuilder;
use DB;
use Hash;
use App\Libraries\ValidateCode;
class LoginController extends Controller
{
    //登录
    public function login()
    {
        // return 222;
    	return view('home.login.login');
    }

    //处理登录（post提交的用Request $request）
    public function doLogin(Request $request)
    {
        $data = $request -> except('_token','code');      
        $this->validate($request, [
            //验证规则，required(不为空)
             'name' => 'required',
            'password' => 'required',
            'code' => 'required',
        ],[
             //错误提醒
             'name.required' => '请输入账号',
             'password.required' => '请输入密码',
             'code.required' => '请输入验证码',             
        ]);
        
        // 检测验证码
        $code = $request -> input('code');
        // dd(session('code'));
        $request -> flash();      
        if($code != session('code'))
        {
            return back() -> with(['error' => '验证码错误']);
        }

        //验证账号
        $name = DB::table('member') -> lists('name');//把name字段以数组的形式查出来
        if(!in_array($data['name'],$name))
        {
            return back() -> with(['error' => '账户名与密码不匹配，请重新输入']);
        }
        
        //查询密码
        $p = DB::table('member') -> where('name','=',$data['name']) -> first() -> password;
        //验证密码
        if (Hash::check($data['password'], $p)) {
           //登入成功
            return redirect('/admin/index');
        }else
        {
            //登录失败
            return back() -> with(['error' => '账户名与密码不匹配，请重新输入']);
        }
    }

    //生成验证码
    public function v_code($id)
    {   
        $vc=new ValidateCode();
        $vc->doimg();
        session(['code' => $vc->getCode()]);        
    }
}
